<?php
// +----------------------------------------------------------------------
// | [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 自定义异常处理
// +----------------------------------------------------------------------
namespace app\common\exception;

use think\exception\Handle;
use think\facade\Request;
use think\facade\Log;

class ExceptionHandler extends Handle
{
  private $code;
  private $msg;
  private $errorCode;
  //需要返回客户端当前请求的URL路径
  public function render(\Exception $e)
  {
    if ($e instanceof BaseException) {
      // 关闭日志记录
      Log::close('file');
      //如果是自定义的异常
      $this->code = $e->code;
      $this->msg = $e->msg;
      $this->errorCode = $e->errorCode;
    }
    else {
      if (env("app_debug")) {
        Log::close('file');
        return parent::render($e);
      }
      else {
        $this->code = 500;
        $this->msg = '服务器内部错误';
        $this->errorCode = 999;
        $this->recordErrorLog($e);
      }
    }
    $result = [
      'msg' => $this->msg,
      'error_code' => $this->errorCode,
      'request_url' => Request::url()
    ];
    return json($result,$this->code);
  }

  // 写入日志
  private function recordErrorLog(\Exception $e){
    Log::record($e->getMessage(),'error');
  }

}
?>